import { Navigate, Outlet } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { useEffect, useState } from 'react'
import type { RootState } from '../store/store'
import { authService } from '../services/auth'

export default function RequireAuth() {
    const accessToken = useSelector((s: RootState) => s.auth.accessToken)
    const [isLoading, setIsLoading] = useState(true)
    const [isInitialized, setIsInitialized] = useState(false)

    useEffect(() => {
        // 检查是否有存储的认证信息
        const checkAuthFromStorage = () => {
            try {
                const storedAuth = localStorage.getItem('auth')
                if (storedAuth) {
                    // 如果有存储的认证信息，尝试恢复状态
                    authService.loadFromStorage()
                }
            } catch (error) {
                console.error('Failed to load auth from storage:', error)
            } finally {
                setIsLoading(false)
                setIsInitialized(true)
            }
        }

        // 延迟检查，确保 Redux store 已经初始化
        const timer = setTimeout(checkAuthFromStorage, 100)
        return () => clearTimeout(timer)
    }, [])

    // 如果还在加载中，显示加载状态
    if (isLoading || !isInitialized) {
        return (
            <div style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                height: '100vh',
                fontSize: '16px',
                color: '#666'
            }}>
                加载中...
            </div>
        )
    }

    // 检查认证状态
    if (!accessToken) {
        return <Navigate to="/login" replace />
    }

    return <Outlet />
}


